//
//  BLAuthSocket.swift
//  danmuDemo
//
//  Created by BigL055 on 16/6/15.
//  Copyright © 2016年 bigL.MoreDemo.com. All rights reserved.
//

import UIKit
import CocoaAsyncSocket

class BLAuthSocket: BLDouyuTVSocket {
    
    static let sharedInstance = BLAuthSocket()
    
    var InfoBlock : ((vistorID : String, groupID : String) -> ())?
    
    override func setServerConfig() {
        //拼接字符串
        let roomAdr :String = "http://www.douyutv.com/\(room)"
        //定义房间的URL
        guard let roomURL : NSURL = NSURL(string: roomAdr) else{
            return
        }
        //讲网页源码转换成字符串
        var htmlCode : NSString
        do{
            htmlCode = try NSString(contentsOfURL: roomURL,encoding: NSUTF8StringEncoding)
            
            //找到相关字典所在的位置并截取
            let serverRange : NSRange = htmlCode.rangeOfString("server_config")
            
            let jsRoomDic : NSString = htmlCode.substringFromIndex(serverRange.location + serverRange.length + 3)
            
            let jsDic : NSRange = jsRoomDic.rangeOfString("def_disp_gg")
            let room_args : NSString = jsRoomDic.substringToIndex(jsDic.location - 3)
            //拿到登陆服务器并decode
            let encodeCfg : NSString = room_args
            let decodeCfg : NSString = encodeCfg.stringByRemovingPercentEncoding!
            let sevIP : NSData = decodeCfg.dataUsingEncoding(NSUTF8StringEncoding)!
            var sevArray : [[String : String]] = [[:]]
            do{
                sevArray = try NSJSONSerialization.JSONObjectWithData(sevIP, options: NSJSONReadingOptions.MutableLeaves) as! [[String : String]]
                
            }catch{
                print(error)
            }
            
            //转换成model，添加到属性
            server = [BLServerModel]()
            for sevCfg : [String : String] in sevArray {
                let model : BLServerModel = BLServerModel()
                model.ip = sevCfg["ip"]
                model.port = UInt16(sevCfg["port"]!)
                server.append(model)
            }
            
        }catch{
            print(error)
        }
        
    }
    
}

// MARK: - 回调方法
extension BLAuthSocket{
    ///连接成功
    override func onSocket(sock: AsyncSocket!, didConnectToHost host: String!, port: UInt16) {
        
        print("---认证服务器连接成功---");
        /*
         验证服务器包
         type@=loginreq/username@=/ct@=0/password@=/roomid@=43053/devid@=479512DA70520865088A9A52B53242FB/rt@=1450509705/vk@=d2494e478b4229e3c98a398c8ae2c8f3/ver@=20150929/
         roomid:房间id
         devid:随机UUID
         rt:时间戳
         vk:时间戳+"7oE9nPEG9xXV69phU31FYCLUagKeYtsF"+devid的字符串拼接结果的MD5值
         ver:版本号
         
         */
        

        
        let devid = String.getUUID()
        let timeString = String.getTimeSince()
        
        let unMD5vk = "\(timeString)\(kMagicCode)\(devid)"
        let vk : String = unMD5vk.md5
        
        let postLogin = "type@=loginreq/username@=/ct@=0/password@=/roomid@=\(room)/devid@=\(devid)/rt@=\(timeString)/vk@=\(vk)/ver@=20150929/"
        let postLoginData = packToData(postLogin)
        socket?.writeData(postLoginData, withTimeout: 30, tag: 1)
    }
    
    override func onSocket(sock: AsyncSocket!, didReadData data: NSData!, withTag tag: Int) {
        
        if data.length != 0 {
            var endCode : NSInteger = 0
            //获取data末尾字节
            data.getBytes(&endCode, range: NSMakeRange(data.length - 1, 1))
            if combieData == nil {
                combieData = NSMutableData()
            }
            //如果为0则代表这是一段完整的数据，可以进行解析
            //若无，则需要拼接至一段完整数据才进行解析
            if endCode == 0 {
                combieData?.appendData(data)
                BLSocketData.douyuData(combieData!, isAuthData: true)
                combieData = nil
            }else{
                combieData?.appendData(data)
            }
        }
        socket?.readDataWithTimeout(kReadTimeOut, buffer: nil, bufferOffset: 0, maxLength: kMaxBuffer, tag: 0)
    }
    
    override func onSocketDidDisconnect(sock: AsyncSocket!) {
        
        print("---认证服务器断开---");
    }
}
